const express = require('express');
const router = express.Router();
const _ = require('lodash');
const jwt = require('jsonwebtoken');
const config = require('../config/env/config_development.json');

const excudeUrl = [
    "/api/merchants/login",
    "/api/merchants/register"
];
router.all("*",function(req,res,next){
   console.log("requestUrl:"+req.originalUrl);
    if(_.indexOf(excudeUrl,req.originalUrl)!=-1){
        next();
    }else{
        console.log(req.originalUrl);
        console.log(req.name);
        //在此判断
        var token = req.headers.authorization;
        if (_.isEmpty(token)){
            res.json({
                code:-1,
                message:"no auth"
            });
        }else{
            try{
                var trueToken = token.split(" ")[1];
                var decoded = jwt.verify(trueToken, config.secret);
                req.merchantId=decoded.id;
                req.name = decoded.name;
                next();
            }catch (error){
                next(new Error(error))
            }


        }

    }

});
module.exports =router;